const { prisma } = require('../config/prisma');

/**
 * 实时监控自动发布功能
 * 每30秒检查一次待审核信息的状态
 */
async function monitorAutoPublish() {
  console.log('=== 自动发布实时监控 ===\n');
  console.log('监控中... (按 Ctrl+C 退出)\n');

  let iteration = 0;

  const checkStatus = async () => {
    iteration++;
    const now = new Date();

    console.log(`\n[${now.toLocaleString('zh-CN')}] 第 ${iteration} 次检查`);
    console.log('─'.repeat(80));

    try {
      // 1. 统计各状态的挂牌信息
      const stats = await prisma.listings.groupBy({
        by: ['audit_status'],
        _count: true
      });

      console.log('\n📊 挂牌信息状态统计:');
      stats.forEach(stat => {
        const statusMap = {
          'PENDING': '待审核',
          'APPROVED': '已通过',
          'REJECTED': '已拒绝'
        };
        console.log(`   ${statusMap[stat.audit_status]}: ${stat._count} 条`);
      });

      // 2. 查询待审核且有自动发布时间的信息
      const pendingWithAutoPublish = await prisma.listings.findMany({
        where: {
          audit_status: 'PENDING',
          auto_publish_at: {
            not: null
          }
        },
        select: {
          id: true,
          company_name: true,
          created_at: true,
          auto_publish_at: true,
          audit_admin_id: true
        },
        orderBy: {
          auto_publish_at: 'asc'
        }
      });

      console.log(`\n⏰ 待审核且设置了自动发布时间的信息: ${pendingWithAutoPublish.length} 条`);

      if (pendingWithAutoPublish.length > 0) {
        pendingWithAutoPublish.forEach((listing, index) => {
          const timeLeft = listing.auto_publish_at - now;
          const minutesLeft = Math.floor(timeLeft / 1000 / 60);
          const secondsLeft = Math.floor((timeLeft / 1000) % 60);

          const status = timeLeft > 0
            ? `⏳ 剩余 ${minutesLeft}分${secondsLeft}秒`
            : `🔥 已超时 ${Math.abs(minutesLeft)}分${Math.abs(secondsLeft)}秒`;

          console.log(`   ${index + 1}. ID:${listing.id} - ${listing.company_name || '(无名称)'}`);
          console.log(`      创建时间: ${listing.created_at.toLocaleString('zh-CN')}`);
          console.log(`      自动发布时间: ${listing.auto_publish_at.toLocaleString('zh-CN')}`);
          console.log(`      ${status}`);
        });
      }

      // 3. 查询待审核但没有自动发布时间的信息（可能是老数据）
      const pendingWithoutAutoPublish = await prisma.listings.findMany({
        where: {
          audit_status: 'PENDING',
          auto_publish_at: null
        },
        select: {
          id: true,
          company_name: true,
          created_at: true
        },
        take: 5
      });

      if (pendingWithoutAutoPublish.length > 0) {
        console.log(`\n⚠️  待审核但未设置自动发布时间的信息: ${pendingWithoutAutoPublish.length} 条（可能是历史数据）`);
        pendingWithoutAutoPublish.forEach((listing, index) => {
          console.log(`   ${index + 1}. ID:${listing.id} - ${listing.company_name || '(无名称)'} - 创建于 ${listing.created_at.toLocaleString('zh-CN')}`);
        });
      }

      // 4. 查询最近被自动发布的信息
      const recentAutoPublished = await prisma.listings.findMany({
        where: {
          audit_status: 'APPROVED',
          audit_comment: {
            contains: '系统自动上架'
          },
          audit_time: {
            gte: new Date(Date.now() - 60 * 60 * 1000) // 最近1小时
          }
        },
        select: {
          id: true,
          company_name: true,
          audit_time: true,
          audit_comment: true
        },
        orderBy: {
          audit_time: 'desc'
        },
        take: 5
      });

      if (recentAutoPublished.length > 0) {
        console.log(`\n✅ 最近1小时内自动发布的信息: ${recentAutoPublished.length} 条`);
        recentAutoPublished.forEach((listing, index) => {
          console.log(`   ${index + 1}. ID:${listing.id} - ${listing.company_name || '(无名称)'}`);
          console.log(`      自动发布时间: ${listing.audit_time.toLocaleString('zh-CN')}`);
        });
      }

      // 5. 查询最近被管理员审核的信息
      const recentManualAudit = await prisma.listings.findMany({
        where: {
          audit_admin_id: {
            not: null
          },
          audit_time: {
            gte: new Date(Date.now() - 60 * 60 * 1000) // 最近1小时
          },
          NOT: {
            audit_comment: {
              contains: '系统自动上架'
            }
          }
        },
        select: {
          id: true,
          company_name: true,
          audit_status: true,
          audit_time: true,
          audit_comment: true,
          auto_publish_at: true
        },
        orderBy: {
          audit_time: 'desc'
        },
        take: 5
      });

      if (recentManualAudit.length > 0) {
        console.log(`\n👨‍💼 最近1小时内管理员审核的信息: ${recentManualAudit.length} 条`);
        recentManualAudit.forEach((listing, index) => {
          const statusMap = {
            'APPROVED': '通过',
            'REJECTED': '拒绝'
          };
          const hasAutoPublishAt = listing.auto_publish_at ? '❌ 仍有auto_publish_at' : '✅ 已清除auto_publish_at';

          console.log(`   ${index + 1}. ID:${listing.id} - ${listing.company_name || '(无名称)'} - ${statusMap[listing.audit_status]}`);
          console.log(`      审核时间: ${listing.audit_time.toLocaleString('zh-CN')}`);
          console.log(`      ${hasAutoPublishAt}`);
        });
      }

      console.log('\n' + '─'.repeat(80));

    } catch (error) {
      console.error('❌ 检查过程中发生错误:', error.message);
    }
  };

  // 立即执行一次
  await checkStatus();

  // 每30秒检查一次
  const intervalId = setInterval(checkStatus, 30000);

  // 优雅退出
  process.on('SIGINT', async () => {
    console.log('\n\n👋 停止监控...');
    clearInterval(intervalId);
    await prisma.$disconnect();
    process.exit(0);
  });
}

// 运行监控
if (require.main === module) {
  monitorAutoPublish().catch(error => {
    console.error('监控失败:', error);
    process.exit(1);
  });
}

module.exports = { monitorAutoPublish };
